//
//  MXAddSetContactController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/3.
//

#import "MXAddSetContactController.h"
#import "MxPublicNav.h"
#import "STLoopProgressView.h"
#import "MXAddSuccessController.h"
#import "DCAlterView.h"
#import "ProgressItemView.h"
#import "DCWifiTool.h"
#import <AFNetworkReachabilityManager.h>

@interface MXAddSetContactController () <MxNavigationViewDelegate>
@property (nonatomic, strong) MxPublicNav *nav;

@property (nonatomic,strong) UIScrollView * scrollView;
@property (nonatomic, strong) STLoopProgressView *rateView;//进度
@property (nonatomic, strong) UILabel *progeressLab;
@property (nonatomic, strong) UILabel *nextLab;

//步骤
@property (nonatomic,strong) UIView * progressView;
@property (nonatomic,strong) UIView * progressFootView;
@property (nonatomic,strong) ProgressItemView * lastItemView;


@property (nonatomic,strong) AFNetworkReachabilityManager * reaManager;//判断网络
@property (nonatomic,strong) NSString * currentWifiName;
@property (nonatomic,assign) AFNetworkReachabilityStatus currentWifiStatus;

@property (nonatomic,assign) NSInteger switchWifiCount;//配网后，检测网络是否断开

@end

@implementation MXAddSetContactController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createUI];
}

- (void)createUI {
    self.currentWifiName = @"";
    
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nav.mas_bottom);
        make.left.bottom.right.equalTo(self.view);
    }];
    
    UILabel *addLab = [[UILabel alloc] initWithFrame:CGRectMake(26, kScalHeight(66), 300, 30)];
    [self.scrollView addSubview:addLab];
    addLab.text = @"与设备建立连接";
    addLab.textColor = [UIColor colorWithHexString:@"#221815"];
    addLab.font = PFRFontMedium(30);
    
    UILabel *tipLab = [[UILabel alloc] initWithFrame:CGRectMake(24, CGRectGetMaxY(addLab.frame) + 31, 200, 14)];
    tipLab.text = @"请将手机靠近设备";
    tipLab.textColor = [UIColor dc_colorWithHexString:@"#000000" alpha:0.7];
    tipLab.font =  PFRFont(14);
    [self.scrollView addSubview:tipLab];
    
    self.rateView = [[STLoopProgressView alloc] initWithFrame:CGRectMake((kScreenW - 220.0) / 2.0, CGRectGetMaxY(tipLab.frame) + 37, 220.0, 212.0)];
    self.rateView.persentage = 0;
    [self.scrollView addSubview:self.rateView];

    self.progeressLab = [[UILabel alloc] init];
    self.progeressLab.textColor = [UIColor colorWithHexString:@"#999999"];
    self.progeressLab.text = @"0%";
    self.progeressLab.font = PFRFontDIN(28);
    [self.scrollView addSubview:self.progeressLab];
    [self.progeressLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.rateView);
    }];
    
    self.progressView = [[UIView alloc] init];
    [self.scrollView addSubview:self.progressView];
    [self.progressView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.top.mas_equalTo(self.rateView.mas_bottom).offset(37);
        make.width.mas_equalTo(kScreenW);
        make.bottom.offset(-120);
    }];
    
    ProgressItemView * itemView = [[ProgressItemView alloc] init];
    [self.progressView addSubview:itemView];
    [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.progressView);
        make.left.right.equalTo(self.progressView);
    }];
    itemView.descLab.dc_text = @"设备信息获取中";
    self.lastItemView = itemView;
    
    self.progressFootView = [[UIView alloc] init];
    [self.progressView addSubview:self.progressFootView];
    [self.progressFootView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.lastItemView.mas_bottom);
        make.left.right.bottom.equalTo(self.progressView);
        make.height.mas_equalTo(1);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    
    self.reaManager;
    
    [self getDeviceInfo];
    
//    UIImageView *progerssImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add_progerss"]];
//    [self.view addSubview:progerssImageV];
//    [progerssImageV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(13);
//        make.height.mas_equalTo(102);
//        make.width.mas_equalTo(324);
//        make.top.mas_equalTo(self.rateView.mas_bottom).offset(37);
//    }];
//    
//    //记得删掉 测试用
//    MJWeakSelf
//    self.nextLab = [[UILabel alloc] init];
//    [self.view addSubview:self.nextLab];
//    self.nextLab.backgroundColor = [UIColor colorWithHexString:@"#3278F6"];
//    self.nextLab.userInteractionEnabled = YES;
//    self.nextLab.textColor = [UIColor whiteColor];
//    self.nextLab.text = @"下一步";
//    self.nextLab.font = PFRFontMedium(16);
//    self.nextLab.textAlignment = NSTextAlignmentCenter;
//    self.nextLab.layer.cornerRadius = 24;
//    self.nextLab.layer.masksToBounds = YES;
//    [self.nextLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
//        [weakSelf nextStep];
//    }]];
//    
//    [self.nextLab mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.offset(14);
//        make.right.offset(-14);
//        make.height.mas_equalTo(48);
//        make.bottom.offset(-50);
//    }];
}

- (void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)nextStep {
    MXAddSuccessController *successVc = [[MXAddSuccessController alloc] init];
    successVc.deviceName = (self.deviceId && self.deviceId.length > 0) ? self.deviceId : self.deviceName;
    successVc.familyId = self.familyId;
    NSMutableArray * arr = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    arr[arr.count - 1] = successVc;
    [self.navigationController setViewControllers:arr animated:YES];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}




#pragma mark - 获取设备信息
-(void)getDeviceInfo{
    MJWeakSelf;
    NSDictionary *param = @{@"familyId":self.familyId?self.familyId:@"",@"categoryId":self.categoryId?self.categoryId:@""};
    [[DCHttpClient shareClient] requestWithPath:@"api/app/device/register" params:param httpMethod:DCHttpRequestJsonPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            NSLog(@"===%@",dict);
            weakSelf.deviceName = dict[@"data"][@"deviceName"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"deviceName"]] : @"";
            weakSelf.devicePsk = dict[@"data"][@"devicePsk"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"devicePsk"]] : @"";
            weakSelf.productId = dict[@"data"][@"productId"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"productId"]] : @"";
            weakSelf.mqttUsername = dict[@"data"][@"userName"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"userName"]] : @"";
            weakSelf.mqttPassword = dict[@"data"][@"pwd"] ? [NSString stringWithFormat:@"%@",dict[@"data"][@"pwd"]] : @"";
            
            [weakSelf.lastItemView success];
            
            ProgressItemView * itemView = [[ProgressItemView alloc] init];
            [weakSelf.progressView addSubview:itemView];
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.equalTo(weakSelf.progressView);
            }];
            itemView.descLab.dc_text = @"设备信息获取成功";
            [itemView success];
            
            ProgressItemView * itemView1 = [[ProgressItemView alloc] init];
            [weakSelf.progressView addSubview:itemView1];
            [itemView1 mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(itemView.mas_bottom);
                make.left.right.equalTo(weakSelf.progressView);
            }];
            itemView1.descLab.dc_text = @"自动连接WIFI失败。\n请手动打开WIFI设置连接到《“Feeder-AP”热点，密码123456789》，连接成功后将自动进行下一步";
            weakSelf.lastItemView = itemView1;
            
            [weakSelf.progressFootView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.bottom.equalTo(weakSelf.progressView);
                make.height.mas_equalTo(1);
            }];
            
            weakSelf.rateView.persentage = 0.2;
            weakSelf.progeressLab.text = @"20%";
            
            [weakSelf detectionDeviceWifiInfo];
        } else {
            [SVProgressHUD showInfoWithStatus:dict[DC_ResultMsg_Key]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf getDeviceInfo];
            });
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf getDeviceInfo];
        });
    }];
}

#pragma mark - 检测wifi是否链接到：Feeder-AP
-(void)detectionDeviceWifiInfo{
    if(self.currentWifiStatus == AFNetworkReachabilityStatusReachableViaWiFi && [self.currentWifiName isEqualToString:@"Feeder-AP"]){
        
        MJWeakSelf;
        [[DCHttpClient shareClient] requestWithBaseUrl:@"http://192.168.1.1:8080/device_info" path:@"" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            
            NSString * str = [responseObject mj_JSONString];
            if(str && str.length > 0){
                //已经配过网了
                NSLog(@"===%@",str);
                str = [str stringByReplacingOccurrencesOfString:@"{deviceId:" withString:@"{\"deviceId\":"];
                NSLog(@"===%@",str);
                NSDictionary * dict = [str mj_JSONObject];
                NSLog(@"===%@",dict);
                weakSelf.deviceId = dict[@"deviceId"] ? [NSString stringWithFormat:@"%@",dict[@"deviceId"]] : @"";
            }
            
            [weakSelf.lastItemView success];
            
            ProgressItemView * itemView = [[ProgressItemView alloc] init];
            [weakSelf.progressView addSubview:itemView];
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.equalTo(weakSelf.progressView);
            }];
            itemView.descLab.dc_text = @"WiFi连接成功";
            [itemView success];
            weakSelf.lastItemView = itemView;
            
            [weakSelf.progressFootView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.bottom.equalTo(weakSelf.progressView);
                make.height.mas_equalTo(1);
            }];
            
            weakSelf.rateView.persentage = 0.5;
            weakSelf.progeressLab.text = @"50%";
            
            if(weakSelf.deviceId && weakSelf.deviceId.length > 0){
//                [weakSelf configWifi];
                [weakSelf configMqtt];
            }else{
                [weakSelf configMqtt];
            }
            
        } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf detectionDeviceWifiInfo];
            });
        }];
    }else{
        MJWeakSelf;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf detectionDeviceWifiInfo];
        });
    }
}

#pragma mark - 配置MQTT
-(void)configMqtt{
    NSLog(@"===configMqtt");
    //http://192.168.1.1:8080/mqtt?username=6KO008S0FFmxg_device_002;12010126;2SEFA;1722591704&userpwd=6cb0059e490f5f0be221fe2ebe667b4206a5a6cd;hmacsha1
    NSString * mqttUrl = [NSString stringWithFormat:@"http://192.168.1.1:8080/mqtt?username=%@&userpwd=%@",self.mqttUsername,self.mqttPassword];
    MJWeakSelf;
    [[DCHttpClient shareClient] requestWithBaseUrl:mqttUrl path:@"" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSString * str = [responseObject mj_JSONString];
        NSInteger code = 0;
        NSLog(@"===%@",str);
        if(str && str.length > 0){
            str = [str stringByReplacingOccurrencesOfString:@"code:" withString:@"\"code\":"];
            str = [str stringByReplacingOccurrencesOfString:@"status:" withString:@"\"status\":"];
            NSLog(@"===%@",str);
            NSDictionary * dict = [str mj_JSONObject];
            NSLog(@"===%@",dict);
            code = dict[@"code"] ? [dict[@"code"] integerValue] : 0;
        }
        NSLog(@"===code:%ld",(long)code);
        if(code == 200){
            [weakSelf.lastItemView success];
            
            ProgressItemView * itemView = [[ProgressItemView alloc] init];
            [weakSelf.progressView addSubview:itemView];
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.equalTo(weakSelf.progressView);
            }];
            itemView.descLab.text = @"设置配网信息成功";
            [itemView success];
            
            ProgressItemView * itemView1 = [[ProgressItemView alloc] init];
            [weakSelf.progressView addSubview:itemView1];
            [itemView1 mas_updateConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(itemView.mas_bottom);
                make.left.right.equalTo(weakSelf.progressView);
            }];
            itemView1.descLab.dc_text = @"正在设置配网wifi账号密码，配网进行中";
            weakSelf.lastItemView = itemView1;
            
            [weakSelf.progressFootView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(weakSelf.lastItemView.mas_bottom);
                make.left.right.bottom.equalTo(weakSelf.progressView);
                make.height.mas_equalTo(1);
            }];
            
            weakSelf.rateView.persentage = 0.7;
            weakSelf.progeressLab.text = @"70%";
            
            [weakSelf configWifi];
            
        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf configMqtt];
            });
        }
        
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf configMqtt];
        });
    }];
}

-(void)configWifi{
    NSString * wifiUrl = [NSString stringWithFormat:@"http://192.168.1.1:8080/setup?ssid=%@&pwd=%@",self.wifiName,self.wifiPwd];
    MJWeakSelf;
    [[DCHttpClient shareClient] requestWithBaseUrl:wifiUrl path:@"" params:@{} httpMethod:DCHttpRequestGet sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSString * str = [responseObject mj_JSONString];
        NSLog(@"===%@",str);
        
        [weakSelf.lastItemView success];
        
        ProgressItemView * itemView = [[ProgressItemView alloc] init];
        [weakSelf.progressView addSubview:itemView];
        [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.lastItemView.mas_bottom);
            make.left.right.equalTo(weakSelf.progressView);
        }];
        itemView.descLab.text = @"WIFI账号密码设置成功! 配网状态检测中";
        weakSelf.lastItemView = itemView;
        
        [weakSelf.progressFootView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.lastItemView.mas_bottom);
            make.left.right.bottom.equalTo(weakSelf.progressView);
            make.height.mas_equalTo(1);
        }];
        
        weakSelf.rateView.persentage = 1;
        weakSelf.progeressLab.text = @"100%";
        
        [weakSelf detectionWifiInfo];
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf configWifi];
        });
    }];
}

#pragma mark - 检测wifi是否切换回网络了
-(void)detectionWifiInfo{
    NSLog(@"===detectionWifiInfo:%@",self.currentWifiName);
    NSLog(@"===detectionWifiInfo:%d",self.currentWifiStatus);
    
    self.switchWifiCount++;
    if(self.switchWifiCount > 10){
        MJWeakSelf;
        DCAlterView * alterView = [[DCAlterView alloc] initWithTitle:@"配网失败" content:@"1、请检查WIFI密码是否正确\n2、请将设备靠近WIFI"];
        [alterView addActionWithTitle:@"知道了" color:[UIColor colorWithHexString:@"#3378F8"] type:DCAlterTypeDone halderBlock:^(UIButton *button) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        
        [DC_KeyWindow addSubview:alterView];
        return;
    }
    
    if(self.currentWifiStatus == AFNetworkReachabilityStatusReachableViaWWAN || (self.currentWifiStatus == AFNetworkReachabilityStatusReachableViaWiFi && ![self.currentWifiName isEqualToString:@"Feeder-AP"])){
        NSLog(@"====网络切回成功");
        [self.lastItemView success];
        
        MXAddSuccessController *successVc = [[MXAddSuccessController alloc] init];
        successVc.deviceName = (self.deviceId && self.deviceId.length > 0) ? self.deviceId : self.deviceName;
        successVc.familyId = self.familyId;
        NSMutableArray * arr = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        arr[arr.count - 1] = successVc;
        [self.navigationController setViewControllers:arr animated:YES];
    }else{
        MJWeakSelf;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf detectionWifiInfo];
        });
    }
    
}

#pragma mark - 检测网络连接状态
-(AFNetworkReachabilityManager *)reaManager{
    if(!_reaManager){
        MJWeakSelf
        _reaManager = [AFNetworkReachabilityManager sharedManager];
        [_reaManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            // 当网络状态改变时调用
            switch (status) {
                    case AFNetworkReachabilityStatusUnknown:
                    NSLog(@"InitNetwork 网络检测结果：未知网络");
                    break;
                    case AFNetworkReachabilityStatusNotReachable:
                    NSLog(@"InitNetwork 网络检测结果：没有网络");
                    break;
                    case AFNetworkReachabilityStatusReachableViaWWAN:
                    NSLog(@"InitNetwork 网络检测结果：手机自带网络");
                    break;
                    case AFNetworkReachabilityStatusReachableViaWiFi:
                    NSLog(@"InitNetwork 网络检测结果：WIFI");
                    break;
            }
            weakSelf.currentWifiStatus = status;
            if(status == AFNetworkReachabilityStatusReachableViaWiFi){
                NSString *wifiName = [[DCWifiTool shareClient] dc_connectWifiName];
                if(wifiName && wifiName.length > 0){
                    NSLog(@"===wifiName：%@",wifiName);
                    weakSelf.currentWifiName = wifiName;
                }else{
                    weakSelf.currentWifiName = @"";
                }
            }
        }];
        [_reaManager startMonitoring];
    }
    return _reaManager;
}

-(void)WillEnterForeground{
    [self.reaManager stopMonitoring];
    [self.reaManager startMonitoring];
}
@end
